<template>
  <div class="user-management">
    <!-- 用户列表区域 -->
    <t-card class="list-card-container" :bordered="false">
      <!-- 集成查询和操作区域 -->
      <search-panel
        v-model:keyword="searchForm.keyword"
        :advanced-fields="advancedFields"
        :buttons="buttons"
        :selected-row-keys="selectedRowKeys"
        basic-placeholder="请输入用户名、姓名或邮箱"
        @search="handleSearch"
        @advanced-search="handleAdvancedSearch"
        @reset="handleReset"
        @button-click="handleButtonClick"
      />

      <data-table
        :data="userList"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        :selected-row-keys="selectedRowKeys"
        :show-toolbar="true"
        :show-actions="true"
        :actions="tableActions"
        @select-change="handleSelectChange"
        @page-change="handlePageChange"
        @action-click="handleActionClick"
      >
        <!-- 状态列 -->
        <template #status="{ row }">
          <t-tag :theme="row.status === 1 ? 'success' : 'danger'" variant="light">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </t-tag>
        </template>

        <!-- 操作列 -->
        <template #actions="{ row }">
          <t-space>
            <t-link theme="primary" @click="handleActionClick({ label: '编辑', handler: handleEdit }, row)">编辑</t-link>
            <t-link theme="danger" @click="handleActionClick({ label: '删除', handler: handleDelete }, row)">删除</t-link>
          </t-space>
        </template>
      </data-table>
    </t-card>



    <!-- 用户编辑弹窗 -->
    <t-dialog
      v-model:visible="showUserDialog"
      :header="dialogTitle"
      width="600px"
      :on-confirm="handleSubmit"
      :on-close="handleDialogClose"
      destroy-on-close
    >
      <t-form :data="userForm" :rules="rules">
        <t-form-item label="用户名" name="username">
          <t-input v-model="userForm.username" placeholder="请输入用户名" :disabled="isEdit" />
        </t-form-item>
        <t-form-item label="真实姓名" name="realname">
          <t-input v-model="userForm.realname" placeholder="请输入真实姓名" />
        </t-form-item>
        <t-form-item label="邮箱" name="email">
          <t-input v-model="userForm.email" placeholder="请输入邮箱" />
        </t-form-item>
        <t-form-item v-if="!isEdit" label="密码" name="password">
          <t-input v-model="userForm.password" type="password" placeholder="请输入密码" />
        </t-form-item>
        <t-form-item label="状态" name="status">
          <t-radio-group v-model="userForm.status">
            <t-radio value="1">启用</t-radio>
            <t-radio value="0">禁用</t-radio>
          </t-radio-group>
        </t-form-item>
      </t-form>
    </t-dialog>

    <!-- 单个用户删除确认对话框 -->
    <t-dialog
      v-model:visible="showDeleteDialog"
      header="确认删除"
      width="400px"
      :on-confirm="executeDelete"
      :on-close="() => showDeleteDialog = false"
      destroy-on-close
    >
      <p>确定要删除用户 "{{ currentDeleteUser?.username }}" 吗？此操作不可恢复。</p>
    </t-dialog>

    <!-- 批量删除确认对话框 -->
    <t-dialog
      v-model:visible="showBatchDeleteDialog"
      header="确认批量删除"
      width="400px"
      :on-confirm="executeBatchDelete"
      :on-close="() => showBatchDeleteDialog = false"
      destroy-on-close
    >
      <p>确定要删除选中的 {{ selectedRowKeys.length }} 个用户吗？此操作不可恢复。</p>
    </t-dialog>
  </div>
</template>
<script setup lang="ts">
import type { PageInfo } from 'tdesign-vue-next';
import { MessagePlugin } from 'tdesign-vue-next';
import { computed, onMounted, reactive, ref } from 'vue';

import type { User as ApiUser } from '@/api/system/user';
import { batchDeleteUsers, createUser, deleteUser, exportUsers, getUserList, updateUser } from '@/api/system/user';
import DataTable from '@/components/DataTable.vue';
import SearchPanel from '@/components/SearchPanel.vue';

// 类型定义
interface User {
  id: number;
  username: string;
  realname: string;
  email: string;
  status: number;
  createAt: string;
  updateAt: string;
}

interface SearchForm {
  keyword: string;
}

interface UserForm {
  id?: number;
  username: string;
  realname: string;
  email: string;
  password: string;
  status: string;
}

// 响应式数据
const loading = ref(false);
const showUserDialog = ref(false);
const showDeleteDialog = ref(false);
const showBatchDeleteDialog = ref(false);
const isEdit = ref(false);
const selectedRowKeys = ref<(string | number)[]>([]);
const currentDeleteUser = ref<User | null>(null);

const searchForm = reactive<SearchForm>({
  keyword: '',
});

const userForm = reactive<UserForm>({
  username: '',
  realname: '',
  email: '',
  password: '',
  status: '1',
});

const userList = ref<User[]>([]);

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});

// 计算属性
const dialogTitle = computed(() => {
  return isEdit.value ? '编辑用户' : '新建用户';
});

// 编辑操作
const handleEdit = (row: User) => {
  isEdit.value = true;
  Object.assign(userForm, {
    id: row.id,
    username: row.username,
    realname: row.realname,
    email: row.email,
    password: '',
    status: row.status.toString(),
  });
  showUserDialog.value = true;
};

// 删除操作
const handleDelete = (row: User) => {
  currentDeleteUser.value = row;
  showDeleteDialog.value = true;
};

// 表格操作配置
const tableActions = [
  {
    label: '编辑',
    type: 'primary',
    icon: 'edit',
    handler: handleEdit
  },
  {
    label: '删除', 
    type: 'danger',
    icon: 'delete',
    handler: handleDelete
  }
];

// 按钮配置 - 开发者可以根据需要自定义按钮
const buttons = [
  {
    name: 'add',
    label: '新建用户',
    theme: 'primary',
    icon: 'add'
  },
  {
    name: 'batchDelete',
    label: '删除用户',
    theme: 'danger',
    icon: 'delete',
    requireSelection: true,
    confirm: true
  },
  {
    name: 'export',
    label: '导出用户',
    theme: 'default',
    icon: 'download'
  }
];

// 高级查询字段配置
const advancedFields = [
  {
    name: 'username',
    label: '用户名',
    type: 'input' as const,
    placeholder: '请输入用户名',
  },
  {
    name: 'realname',
    label: '真实姓名',
    type: 'input' as const,
    placeholder: '请输入真实姓名',
  },
  {
    name: 'email',
    label: '邮箱',
    type: 'input' as const,
    placeholder: '请输入邮箱',
  },
  {
    name: 'status',
    label: '状态',
    type: 'select' as const,
    placeholder: '请选择状态',
    options: [
      { label: '启用', value: '1' },
      { label: '禁用', value: '0' },
    ],
  },
  {
    name: 'createAt',
    label: '创建时间',
    type: 'date-range' as const,
    placeholder: ['开始时间', '结束时间'],
  },
];

// 表单验证规则
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  realname: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' },
  ],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
};

// 表格列配置
const columns = [
  { colKey: 'row-select', title: '', type: 'multiple', width: 30, fixed: 'left' },
  { title: 'ID', colKey: 'id', width: 80, fixed: 'left' },
  { title: '用户名', colKey: 'username', width: 120 },
  { title: '真实姓名', colKey: 'realname', width: 120 },
  { title: '邮箱', colKey: 'email', width: 200 },
  { title: '状态', colKey: 'status', width: 100 },
  { title: '创建时间', colKey: 'createAt', width: 180 }
] as const;

// 生命周期
onMounted(() => {
  fetchUserList();
});

// 方法
const fetchUserList = async (advancedParams?: Record<string, any>) => {
  loading.value = true;
  try {
    // 准备请求参数
    const params: any = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword,
      ...advancedParams, // 将高级查询参数展开到顶层
    };

    // 清空空值参数
    Object.keys(params).forEach((key) => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key];
      }
    });

    console.log('开始调用后端接口，参数:', params);

    const response = await getUserList(params);

    console.log('后端接口响应:', response);

    userList.value = response.list;
    pagination.total = response.total;
    // 适配后端返回的字段名
    if (response.pageSize) {
      pagination.pageSize = response.pageSize;
    }
  } catch (error) {
    console.error('获取用户列表失败，错误详情:', error);
    MessagePlugin.error('获取用户列表失败');
  } finally {
    loading.value = false;
  }
};

const handleSearch = (keyword?: string) => {
  if (keyword !== undefined) {
    searchForm.keyword = keyword;
  }
  pagination.current = 1;
  fetchUserList();
};

const handleReset = () => {
  searchForm.keyword = '';
  pagination.current = 1;
  fetchUserList();
};

const handleAdvancedSearch = (advancedData?: Record<string, any>) => {
  pagination.current = 1;
  fetchUserList(advancedData);
};

const handleAdd = () => {
  isEdit.value = false;
  Object.assign(userForm, {
    id: undefined,
    username: '',
    realname: '',
    email: '',
    password: '',
    status: '1',
  });
  showUserDialog.value = true;
};



const handleBatchDelete = async () => {
  if (selectedRowKeys.value.length === 0) return;

  try {
    await batchDeleteUsers(selectedRowKeys.value as number[]);
    MessagePlugin.success('批量删除成功');
    selectedRowKeys.value = [];
    fetchUserList();
  } catch (error) {
    MessagePlugin.error('批量删除失败');
  }
};

const handleExport = async () => {
  try {
    const blob = await exportUsers({
      ...searchForm,
      ...advancedForm,
    });

    // 创建下载链接
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `用户列表_${new Date().getTime()}.xlsx`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    MessagePlugin.success('导出成功');
  } catch (error) {
    console.error('导出失败，错误详情:', error);
    MessagePlugin.error('导出失败');
  }
};

const handleSubmit = async () => {
  try {
    if (isEdit.value) {
      await updateUser(userForm.id!, {
        realname: userForm.realname,
        email: userForm.email,
        status: Number.parseInt(userForm.status),
      });
    } else {
      await createUser({
        username: userForm.username,
        realname: userForm.realname,
        email: userForm.email,
        password: userForm.password,
        status: Number.parseInt(userForm.status),
      });
    }

    MessagePlugin.success(isEdit.value ? '用户更新成功' : '用户创建成功');
    showUserDialog.value = false;
    fetchUserList();
  } catch (error) {
    MessagePlugin.error(isEdit.value ? '用户更新失败' : '用户创建失败');
  }
};

const handleDialogClose = () => {
  showUserDialog.value = false;
};

const handleSelectChange = (keys: (string | number)[]) => {
  selectedRowKeys.value = keys;
};

// 处理表格操作点击
const handleActionClick = (action: any, row: any) => {
  action.handler(row);
};

// 删除操作执行函数
const executeDelete = async () => {
  if (currentDeleteUser.value) {
    try {
      await deleteUser(currentDeleteUser.value.id!);
      MessagePlugin.success('用户删除成功');
      showDeleteDialog.value = false;
      currentDeleteUser.value = null;
      fetchUserList();
    } catch (error) {
      MessagePlugin.error('用户删除失败');
    }
  }
};

const executeBatchDelete = async () => {
  try {
    await batchDeleteUsers(selectedRowKeys.value as number[]);
    MessagePlugin.success('批量删除成功');
    showBatchDeleteDialog.value = false;
    selectedRowKeys.value = [];
    fetchUserList();
  } catch (error) {
    MessagePlugin.error('批量删除失败');
  }
};

const handlePageChange = (pageInfo: PageInfo) => {
  pagination.current = pageInfo.current;
  pagination.pageSize = pageInfo.pageSize;
  fetchUserList();
};

// 按钮点击事件处理
const handleButtonClick = async (buttonName: string, data?: any) => {
  console.log('按钮点击:', buttonName, '数据:', data);
  
  switch (buttonName) {
    case 'add':
      handleAdd();
      break;
    case 'batchDelete':
      handleBatchDelete();
      break;
    case 'export':
      handleExport();
      break;
    default:
      console.warn('未知按钮:', buttonName);
  }
};
</script>
<style lang="less" scoped>
.user-management {
  .list-card-container {
    padding: var(--td-comp-paddingTB-xxl) var(--td-comp-paddingLR-xxl);

    :deep(.t-card__body) {
      padding: 0;
    }
  }
}
</style>
